package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.CatalogDao;
import com.itheima.domain.Catalog;
import com.itheima.service.CatalogService;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.UUID;

public class CatalogServiceImpl implements CatalogService {
    @Override
    public PageInfo findByPage(int currentPage) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CatalogDao mapper = sqlSession.getMapper(CatalogDao.class);
        PageHelper.startPage(currentPage,5);
        List<Catalog> list = mapper.findAll();
        PageInfo pageInfo = new PageInfo(list);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public void add(Catalog catalog) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CatalogDao mapper = sqlSession.getMapper(CatalogDao.class);
        String id = UUID.randomUUID().toString();
        catalog.setId(id);
        mapper.add(catalog);
        sqlSession.close();
    }

    @Override
    public void update(Catalog catalog) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CatalogDao mapper = sqlSession.getMapper(CatalogDao.class);
        mapper.update(catalog);
        sqlSession.close();
    }

    @Override
    public void delete(String id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CatalogDao mapper = sqlSession.getMapper(CatalogDao.class);
        mapper.delete(id);
        sqlSession.close();
    }

    @Override
    public List<Catalog> findAll() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CatalogDao mapper = sqlSession.getMapper(CatalogDao.class);
        List<Catalog> list = mapper.findAll();
        sqlSession.close();
        return list;
    }
}
